package com.lx.wxdemo.utils;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Description TODO
 * @Author lx
 * @Date 2021/1/5 10:41
 **/
public class RedisUtils {

    /**
     * 根据code换取openId
     * 本接口应在后端服务器调用
     */
    @Value("${CODE_URL}")
    private String CODE_URL;

    @Value("${APP_ID}")
    private String APP_ID;

    @Value("${SECRET}")
    private String SECRET;

    /**
     * 获取小程序codeid换取openid
     *
     * @param codeId
     * @return
     */
    public String getOpenId(String codeId) {
        String url = CODE_URL + APP_ID + "&secret=" + SECRET + "&js_code=" + codeId + "&grant_type=authorization_code";
        PrintWriter out = null;
        BufferedReader in = null;
        String line;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();

            // 设置通用的请求属性 设置请求格式
            //设置返回类型
            conn.setRequestProperty("contentType", "text/plain");
            //设置请求类型
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            //设置超时时间
            conn.setConnectTimeout(1000);
            conn.setReadTimeout(1000);
            conn.setDoOutput(true);
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应    设置接收格式
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            while ((line = in.readLine()) != null) {
                stringBuffer.append(line);
            }
//            JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
            JSONObject jsonObject = JSONObject.fromObject(stringBuffer.toString());
            return jsonObject.get("openid").toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

}
